package com.bz.common;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping(value = "/admin/file")
public class FileUpload {

    private static final Logger log = LoggerFactory.getLogger(FileUpload.class);

    /**
     * 文件上传路劲
     */
    @Value("${web.file.uploadPath}")
    private String              uploadPath;

    @Value("${web.file.url}")
    private String              url;

    @RequestMapping(value = "/upload", method = { RequestMethod.GET, RequestMethod.POST })
    public ResponseDto<Map<String, String>> upload(HttpServletRequest request, @RequestParam MultipartFile file) throws Exception {
        Map<String, String> resMap = new HashMap<>();
        resMap.put("code", "1");
        String fileNameSuffix = file.getOriginalFilename();
        int size = (int) file.getSize();
        if (size > 50000000) {
            resMap.put("code", "0");
            resMap.put("msg", "上传文件大于50M");
            log.error("上传文件大于50M");
            return new ResponseDto<>(resMap);
        }

        Integer index = StringUtils.lastIndexOf(fileNameSuffix, ".");
        String fileName = StringUtils.substring(fileNameSuffix, 0, index);
        String suffix = StringUtils.substring(fileNameSuffix, index + 1, fileNameSuffix.length());

        String filePath = File.separator +
                          DateUtlis.dateToString(new Date(), "yyyyMMdd") +
                          File.separator +
                          DigestUtils.md5Hex(fileName) +
                          "_" +
                          DateUtlis.dateToString(new Date(), "yyyyMMddHHmmss") +
                          "." +
                          suffix;
        File f = new File(uploadPath + filePath);
        File localFolder = f.getParentFile();
        if (!localFolder.exists()) {
            Files.createDirectories(Paths.get(localFolder.getPath()));
        }
        FileUtils.copyInputStreamToFile(file.getInputStream(), f);
        String path = url + filePath;
        resMap.put("url", path);
        resMap.put("name", fileName);
        resMap.put("suffix", suffix);
        return new ResponseDto<>(resMap);
    }

    /**
     * 富 文本用
     * 
     * @param request
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/upload-content", method = { RequestMethod.GET, RequestMethod.POST })
    public Map<String, Object> uploadContent(HttpServletRequest request, @RequestParam MultipartFile file) throws Exception {
        Map<String, Object> resMap = new HashMap<>();
        resMap.put("code", 0);
        resMap.put("msg", "");
        String fileNameSuffix = file.getOriginalFilename();
        int size = (int) file.getSize();
        if (size > 10000000) {
            resMap.put("code", "1");
            resMap.put("msg", "上传文件大于10M");
            log.error("上传文件大于10M");
            return resMap;
        }

        Integer index = StringUtils.indexOf(fileNameSuffix, ".");
        String fileName = StringUtils.substring(fileNameSuffix, 0, index);
        String suffix = StringUtils.substring(fileNameSuffix, index + 1, fileNameSuffix.length());

        String filePath = File.separator +
                          DateUtlis.dateToString(new Date(), "yyyyMMdd") +
                          File.separator +
                          fileName +
                          "_" +
                          DateUtlis.dateToString(new Date(), "yyyyMMddHHmmss") +
                          "." +
                          suffix;
        File f = new File(uploadPath + filePath);
        File localFolder = f.getParentFile();
        if (!localFolder.exists()) {
            Files.createDirectories(Paths.get(localFolder.getPath()));
        }
        FileUtils.copyInputStreamToFile(file.getInputStream(), f);
        String path = filePath;
        Map<String, String> data = new HashMap<>();
        data.put("src", url + path);
        data.put("title", fileName);
        resMap.put("data", data);
        return resMap;
    }
}
